<template>
  <div>
    <basic-container>
      <avue-form :option="option"
                 v-model="form"
                 @tab-click="handleTabClick"
                 @submit="handleSubmit"></avue-form>
    </basic-container>
  </div>
</template>

<script>
import option from "@/const/user/info";
import {getUserInfo, update, updatePassword} from "@/api/system/user";
import func from "@/util/func";


export default {
  data() {
    return {
      index: 0,
      option: option,
      form: {}
    };
  },
  created() {
    this.handleWitch();
  },
  methods: {
    handleSubmit(form, done) {
      if (this.index === 0) {
        update(form).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "修改信息成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
          done();
        }, error => {
          window.console.log(error);
          done();
        })
      } else {
        if (form.newPassword !== form.newPassword1) {
          this.$message({
            type: "warning",
            message: "两次输入密码不一致!"
          });
          done();
          return 0
        }
        console.log(form)
        let params = {
          // account: form.account,
          oldPassword: form.oldPassword,
          newPassword: form.newPassword,
        }
        this.$confirm('修改密码后需重新登录，是否修改!', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: "warning"
        }).then(() => {
          updatePassword(params).then(res => {
            if (res.data.success) {
              this.logout()
            } else {
              this.$message({
                type: "error",
                message: res.data.msg
              });
            }
            done();
          }, error => {
            window.console.log(error);
            done();
          })
        }).catch(() => {
          done();
        });
      }
    },
    // 退出登录
    logout() {
      this.$confirm('密码修改成功，请重新登录!', {
        confirmButtonText: '确定',
        showCancelButton: false, //是否显示取消按钮
        showClose: false,//隐藏右上角的×
        // cancelButtonText: this.$t("cancelText"),
        type: "warning"
      }).then(() => {
        this.$store.dispatch("LogOut").then(() => {
          this.$router.push({path: "/login"});
        });
      });
    },
    handleWitch() {
      if (this.index === 0) {
        getUserInfo().then(res => {
          const user = res.data.data;
          this.form = {
            id: user.id,
            avatar: user.avatar,
            name: user.name,
            realName: user.realName,
            phone: user.phone,
            email: user.email,
          }
        });
      }
    },
    handleTabClick(tabs) {
      this.index = func.toInt(tabs.index);
      this.handleWitch();
    }
  }
};
</script>

<style>
</style>
